package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.HashUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result login(LoginFormDTO loginForm) {
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        String password = loginForm.getPassword();
        //检验手机号是否合法
        if (RegexUtils.isPhoneInvalid(phone)) {
            //不合法则返回
            return Result.fail("手机号不合法！");
        }
        //校验验证码
        if (code == null || code.length() != 6 ) {
            return Result.fail("验证码不合法！");
        }
        if (!code.equals(stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY+phone))) {
            return Result.fail("验证码错误！");
        }
        //检验用户是否存在
        User user = query().eq("phone", phone).one();
        //不存在，添加用户到数据库
        if (user == null) {
            user = createNewUserWithPhone(phone);
        }
        //将用户保存到threadlocal中
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        UserHolder.saveUser(userDTO);
        //将用户保存到redis中
        //生成token
        String token = UUID.randomUUID().toString(true);
        //用户转为hashmap存储
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);
        String id = userMap.get("id").toString();
        userMap.remove("id");
        userMap.put("id", id);
        //保存
        String tokenKey=RedisConstants.LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        stringRedisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);
        return Result.ok(token);
    }


    private User createNewUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setPassword("123456");
        user.setNickName("user_"+ RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
